package com.kmproject.haifu.app.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.irozon.library.HideKey;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.CustomPopupWindow;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.hfinterface.AliYunUploadFileInterface;
import com.kmproject.haifu.app.hfinterface.BtnClickCallBack;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.ResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseMainBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseRentListShowBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseRentListShowInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberCenterUserInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserLoginBean;
import com.kmproject.haifu.mvp.presenter.HouseRentingShowMainPresenter;
import com.kmproject.haifu.mvp.ui.activity.HfRechargeCenterActivity;
import com.kmproject.haifu.mvp.ui.activity.HouseRentingShowDuanZuListActivity;
import com.kmproject.haifu.mvp.ui.activity.HouseRentingShowMainActivity;
import com.kmproject.haifu.mvp.ui.activity.NoticeRentSeekingActivity;
import com.kmproject.haifu.mvp.ui.activity.RentSeekingListActivity;
import com.kmproject.haifu.mvp.ui.activity.SecondHandMainShowActivity;
import com.kmproject.haifu.mvp.ui.adapter.ShareAdapter;
import com.kmproject.haifu.mvp.ui.holder.PopuwindowSecondHandSearchViewHold;
import com.kmproject.haifu.mvp.ui.bis.share.ShareUtil;
import com.kmproject.haifu.wxapi.WxApiUtils;
import com.liji.imagezoom.util.ImageZoom;
import com.tencent.mm.sdk.constants.Build;

import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

public class AppUtil {
    public static boolean isDialogShow = false;

    public AppUtil() {
        throw new AssertionError("你不能初始化工具类");
    }

    /**
     * 去消息列表
     * @param activity
     */
  public static  void  gotoMessage(Activity activity)
  {
      Intent intent=new Intent(activity, NoticeRentSeekingActivity.class);
      ArmsUtils.startActivity(intent);
  }
    /**
     * 楼层统一处理
     *
     * @param item
     * @return
     */
    public static String showFloor(HouseRentListShowInfoBean item) {
        String temFloor = "";
        if (item.getFloorName() != null && !TextUtils.isEmpty(item.getFloorName())) {
            temFloor += item.getFloorName().replace("层", "");
        }
        if (item.getToFloorName() != null && !TextUtils.isEmpty(item.getToFloorName())) {
            if (!TextUtils.isEmpty(temFloor)) {
                temFloor += ("~" + item.getToFloorName().replace("层", ""));
            } else {
                temFloor += item.getToFloorName().replace("层", "");
            }
        }
        if (item.getTotalFloorName() != null && !TextUtils.isEmpty(item.getTotalFloorName())) {
            if (!TextUtils.isEmpty(temFloor)) {
                temFloor += ("/" + item.getTotalFloorName().replace("共", ""));
            } else {
                temFloor += item.getTotalFloorName().replace("共", "");
            }
        }
        return temFloor;
    }

    /**
     * 楼层统一处理
     *
     * @param item
     * @return
     */
    public static String showFloor(HouseRentListShowBean item) {
        String temFloor = "";
        if (item.getFloorName() != null && !TextUtils.isEmpty(item.getFloorName())) {
            temFloor += item.getFloorName().replace("层", "");
        }
        if (item.getToFloorName() != null && !TextUtils.isEmpty(item.getToFloorName())) {
            if (!TextUtils.isEmpty(temFloor)) {
                temFloor += ("~" + item.getToFloorName().replace("层", ""));
            } else {
                temFloor += item.getToFloorName().replace("层", "");
            }
        }
        if (item.getTotalFloorName() != null && !TextUtils.isEmpty(item.getTotalFloorName())) {
            if (!TextUtils.isEmpty(temFloor)) {
                temFloor += ("/" + item.getTotalFloorName().replace("共", ""));
            } else {
                temFloor += item.getTotalFloorName().replace("共", "");
            }
        }
        return temFloor;
    }

    /**
     * 查看大图
     *
     * @param activity
     * @param curreyImngUrl 当前默认显示的url
     * @param allImgsUrl    所有图片的url
     */
    public static void lookBigImg(Activity activity, String curreyImngUrl, List<String> allImgsUrl) {
        ImageZoom.show(activity, curreyImngUrl, allImgsUrl);
    }

    /**
     * 号码统一处理
     *
     * @param phone
     * @return
     */
    public static String mobil(String phone) {
        if (phone == null || TextUtils.isEmpty(phone))
            return "";
        return "+" + phone.substring(0, 2) + " " + phone.substring(2, phone.length());
    }

    /**
     * 控制popu显示
     */
    public static CustomPopupWindow showPopuWindow(Activity activity, View contentView, View parentView) {
//        R.layout.user_popuwindow_view
//        CustomPopupWindow.inflateView(activity, layoutId)
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder().contentView(contentView).parentView(parentView).backgroundDrawable(activity.getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isWrap(true).isHaveBackGround(true).isFocus(false).isDialog(true).isOutsideTouch(false).build();
        View view1 = customPopupWindow.getContentView();
        customPopupWindow.show();
        return customPopupWindow;
    }

    /**
     * 钱格式化
     *
     * @param msg
     * @return
     */
    public static String moneyForat(String msg) {
        if (msg == null || TextUtils.isEmpty(msg)) {
            return msg;
        }
//        String msg=getShowMenoy_new(Double.parseDouble(temmsg));
        if (msg.length() < 3 || !msg.contains(".")) {
            return msg;
        }
        if (msg.substring(msg.lastIndexOf(".") + 1, msg.length()).equals("00") || msg.substring(msg.lastIndexOf(".") + 1, msg.length()).equals("0")) {
            return msg.substring(0, msg.lastIndexOf("."));
        }
        if (msg.substring(msg.length() - 3, msg.length()).equals("000")) {
            return msg.substring(0, msg.length() - 3);
        }
        if (msg.substring(msg.length() - 2, msg.length()).equals("00")) {
            return msg.substring(0, msg.length() - 2);
        }
        if (msg.substring(msg.length() - 1, msg.length()).equals("0")) {
            return msg.substring(0, msg.length() - 1);
        }
        return msg;
    }

    public static String getShowMenoy_new(double oldMoney) {
        if (oldMoney > 100000) {
            return String.format("%.2f", ((double) oldMoney / 10000)) + "万";
        } else {
            return String.valueOf(oldMoney);
        }
    }

    /**
     * 检测是否支持微信支付
     *
     * @param context
     * @return
     */
    public static boolean isWxAppInstalledAndSupported(Context context) {
        if (WxApiUtils.getWxApi(context).getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 控制钱的四舍五入
     *
     * @param oldMoney
     * @return
     */
    public static String getShowMenoy(double oldMoney) {
        if (oldMoney < 10000) {
            return String.valueOf(oldMoney);
        } else if (oldMoney > 10000) {
            return String.format("%.2f", ((double) oldMoney / 10000)) + "万";
        } else {
            return String.valueOf(oldMoney);
        }
    }

    /**
     * 跳转不同的模块
     *
     * @param houseMainItem
     */
    public static void gotoActivityForType(HouseMainBean.HouseMainItem houseMainItem) {
        if ("rentShow".equals(houseMainItem.getType())) {
            //租房模块
            if (houseMainItem.getCode().equals("zz") || houseMainItem.getCode().equals("hz") || houseMainItem.getCode().equals("dz")) {
                Intent intent = new Intent(AppManager.getAppManager().getCurrentActivity(), HouseRentingShowDuanZuListActivity.class);
                intent.putExtra("type", houseMainItem.getCode());
                ArmsUtils.startActivity(intent);
            } else {
//                ArmsUtils.makeText(AppManager.getAppManager().getCurrentActivity(), "功能完善中");
            }
        } else if ("home".equals(houseMainItem.getType())) {
            switch (houseMainItem.getCode()) {
                case "shjf":
                    ArmsUtils.startActivity(HfRechargeCenterActivity.class);
                    break;
                case "zf":
                    ArmsUtils.startActivity(HouseRentingShowMainActivity.class);
                    break;
                case "qz":
                    ArmsUtils.startActivity(RentSeekingListActivity.class);
                    break;
                case "essc":
                    ArmsUtils.startActivity(SecondHandMainShowActivity.class);
                    break;
            }
        }
    }

    /**
     * 判断用户是登录
     *
     * @param activity
     * @return
     */
    public static boolean userIsLogin(Activity activity) {
        UserLoginBean userLoginBean = DataHelper.getDeviceData(activity, AppConstant.LOGUSER_LOGIN_INFOIN);//判断用户是否登陆
        UserBean userBean = DataHelper.getDeviceData(activity, AppConstant.USER_INFO);//获取用户信息

        if (userBean != null && userLoginBean != null && !TextUtils.isEmpty(userLoginBean.getAccess_token())) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 会员中心快要到期提示
     *
     * @param activity
     * @param mParentView
     */
    public static void memberCenterMainPopuWindow(Activity activity, View mParentView, MemberCenterUserInfoBean memberCenterUserInfoBean) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder().parentView(mParentView).contentView(CustomPopupWindow.inflateView(activity, R.layout.membercentermain_top_popuwindow)).backgroundDrawable(activity.getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isViewBottom(true).isFocus(false).isOutsideTouch(false).build();
        View view = customPopupWindow.getContentView();
        ImageView closeView = view.findViewById(R.id.membercentermain_top_popuwindow_img);
        TextView membercentermain_top_popuwindow_txt = view.findViewById(R.id.membercentermain_top_popuwindow_txt);
        membercentermain_top_popuwindow_txt.setText("温馨提示：您的" + memberCenterUserInfoBean.getMemberLevel().getLevelName() + (memberCenterUserInfoBean.getResidualTimeDay() == 1 ? "今" : memberCenterUserInfoBean.getResidualTimeDay()) + "天后过期，过期后所有会员权益将失效，请及时续费！");
        closeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopupWindow.dismiss();

            }
        });
        customPopupWindow.show();

    }

    /**
     * 分享弹框
     */
    public static void sharePopuWindow(Activity activity, View mParentView) {
        sharePopuWindow(activity, mParentView, "海服", "http://www.haifu365.com", "昆明海亲虎服信息科技有限公司，是一家专注于服务海外华人的信息科技公司，目前在菲律宾拥有一家独立子公司，在菲律宾的主要服务有生活缴费，外卖订餐，新闻信息，国际快递，翻译，办证等商务服务，未来规划会在泰国，缅甸，老挝等亚洲国家扩展业务",
                "http://www.haifu365.com/assets/images/heroarea/one/full.png", "http://www.haifu365.com");
    }

    /**
     * 分享弹框
     * @param title title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
     * @param titleUrl titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
     * @param content text是分享文本，所有平台都需要这个字段
     * @param imgUrl 分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
     * @param url url仅在微信（包括好友和朋友圈）中使用
     */
    public static void sharePopuWindow(Activity activity, View mParentView, String title, String titleUrl, String content, String imgUrl, String url) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder().parentView(mParentView).contentView(CustomPopupWindow.inflateView(activity, R.layout.popuwindow_share)).backgroundDrawable(activity.getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isWrap(true).isHaveBackGround(true).isShowBottom(true).build();
        View view1 = customPopupWindow.getContentView();
        RecyclerView popuwindow_share_RecyclerView = view1.findViewById(R.id.popuwindow_share_RecyclerView);
        TextView popuwindow_share_cancel_txt = view1.findViewById(R.id.popuwindow_share_cancel_txt);
        popuwindow_share_RecyclerView.setLayoutManager(new GridLayoutManager(activity, 4));
        List<HouseMainBean.HouseMainItem> houseMainItems = new ArrayList<>();
        houseMainItems.add(new HouseMainBean.HouseMainItem("wx", "微信", R.drawable.share_wx_icon));
        houseMainItems.add(new HouseMainBean.HouseMainItem("pyq", "朋友圈", R.drawable.share_pyq_icon));
        houseMainItems.add(new HouseMainBean.HouseMainItem("qqhy", "QQ好友", R.drawable.share_qq_icon));
        houseMainItems.add(new HouseMainBean.HouseMainItem("wb", "微博", R.drawable.share_wb_icon));
        ShareAdapter sharehAdapter = new ShareAdapter(houseMainItems);
        popuwindow_share_RecyclerView.setAdapter(sharehAdapter);
        sharehAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HouseMainBean.HouseMainItem item = sharehAdapter.getItem(position);

                assert item != null;
                switch (item.getCode()) {
                    case "wx":
                        ShareUtil.INSTANCE.showShare(Wechat.NAME, title, titleUrl, content,
                                imgUrl, url);
                        break;
                    case "pyq":
                        ShareUtil.INSTANCE.showShare(WechatMoments.NAME, title, titleUrl, content,
                                imgUrl, url);
                        break;
                    case "qqhy":
                        ShareUtil.INSTANCE.showShare(QQ.NAME, title, titleUrl, content,
                                imgUrl, url);
                        break;
                    case "wb":
                        ShareUtil.INSTANCE.showShare(SinaWeibo.NAME, title, titleUrl, content,
                                "", url);
                        break;
                }
            }
        });

        popuwindow_share_cancel_txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopupWindow.dismiss();
            }
        });
        customPopupWindow.show();
    }

    /**
     * 设置空view
     *
     * @param activity
     * @param ts
     * @param referTxt
     * @param btnClickCallBack
     * @return
     */
    public static View setEmptyView(Activity activity, String ts, String referTxt, BtnClickCallBack btnClickCallBack, boolean ishindBtn) {
        View view = LayoutInflater.from(activity).inflate(R.layout.empty_view, null);

        if (ts != null && !TextUtils.isEmpty(ts)) {
            TextView mts = view.findViewById(R.id.empty_view_ts_txt);
            mts.setText(ts);
        }
        TextView mreferTxt = view.findViewById(R.id.empty_view_refersh_txt);
        if (referTxt != null && !TextUtils.isEmpty(referTxt)) {
            mreferTxt.setText(referTxt);
        }
        //是否隐藏按钮
        if (ishindBtn) {
            mreferTxt.setVisibility(View.GONE);
        }
        if (btnClickCallBack != null) {
            mreferTxt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (btnClickCallBack != null) {
                        btnClickCallBack.callback(v);
                    }
                }
            });
        }
        return view;
    }

    public static int dp2px(float dpValue) {
        return (int) (0.5f + dpValue * Resources.getSystem().getDisplayMetrics().density);
    }

    /**
     * 实体类转Map
     *
     * @param object
     * @return
     */
    public static Map<String, Object> entityToMap(Object object) {
        Map<String, Object> map = new HashMap();
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                boolean flag = field.isAccessible();
                field.setAccessible(true);
                Object o = field.get(object);
                if (o != null) {
                    map.put(field.getName(), o);
                }

                field.setAccessible(flag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 实体类转Map，处理有父类的情况
     *
     * @param object
     * @return
     */
    public static Map<String, Object> entityToMapHasSuperClazz(Object object) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Field> fieldList = new ArrayList<>();
        Class tempClazz = object.getClass();
        while (tempClazz != null) {
            fieldList.addAll(Arrays.asList(tempClazz.getDeclaredFields()));
            tempClazz = tempClazz.getSuperclass();
        }

        for (Field field : fieldList) {
            try {
                boolean flag = field.isAccessible();
                field.setAccessible(true);
                Object o = field.get(object);
                if (o != null) {
                    map.put(field.getName(), o);
                }

                field.setAccessible(flag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 上传图片到阿里云
     *
     * @param context
     * @param path
     * @param aliYunUploadFileInterface
     */
    public static void upfileToAli(Context context, String filePackage, String path, AliYunUploadFileInterface aliYunUploadFileInterface) {
        // ACCESS_ID,ACCESS_KEY是在阿里云申请的
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Api.accessKeyId, Api.accessKeySecret);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(30 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(8); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        // oss为全局变量，OSS_ENDPOINT是一个OSS区域地址
        OSS oss = new OSSClient(context, "https://" + Api.endpoint, credentialProvider, conf);
        // 构造上传请求。
        String filepPthName = filePackage + "/" + System.currentTimeMillis() + "_" + path.substring(path.lastIndexOf("/") + 1, path.length());
        PutObjectRequest put = new PutObjectRequest(Api.bucketName, filepPthName, path);
// 异步上传时可以设置进度回调。
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                aliYunUploadFileInterface.AliYunUploadFileCallBackProgress(currentSize, totalSize);
            }
        });
        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
//                url += "http://你的BucketName.你的Endpoint/自定义路径/" + fileName;
                aliYunUploadFileInterface.AliYunUploadFileCallBackSuccess(result, "https://" + Api.bucketName + "." + Api.endpoint + "/" + filepPthName);

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    aliYunUploadFileInterface.AliYunUploadFileCallBackFailure(serviceException);
                }
            }
        });
// task.cancel(); // 可以取消任务。
// task.waitUntilFinished(); // 等待任务完成。
    }

    /**
     * 结果校验
     *
     * @param resultBean
     * @return
     */
    public static boolean isSuccess(ResultBean resultBean) {
        if (resultBean == null || resultBean.getCode() != AppConstant.success) {
            return false;
        }
        return true;
    }

    /**
     * 成功提示tost
     *
     * @param context
     * @param str
     */
    public static void midToast(Activity context, String str) {
        LayoutInflater inflater = context.getLayoutInflater();
        View view = inflater.inflate(R.layout.view_toast_custom,
                (ViewGroup) context.findViewById(R.id.lly_toast));
        ImageView img_logo = (ImageView) view.findViewById(R.id.img_logo);
        TextView tv_msg = (TextView) view.findViewById(R.id.tv_msg);
        tv_msg.setText(str);
        Toast toast = new Toast(context);   //mContext为上下文
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(view);
        toast.show();
    }


    /**
     * 通过uri获取bitmap
     *
     * @param uri
     * @return
     */
    public static void getBitmapFromUri(Context context, Uri uri) {
        try {
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
            saveImageToGallery(context, bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "haifu";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getFromMediaUri(Context context, ContentResolver resolver, Uri uri) {
        if (uri == null) return null;

        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
            if (pfd == null) {
                return null;
            }
            FileDescriptor fd = pfd.getFileDescriptor();
            input = new FileInputStream(fd);

            String tempFilename = getTempFilename(context);
            output = new FileOutputStream(tempFilename);

            int read;
            byte[] bytes = new byte[4096];
            while ((read = input.read(bytes)) != -1) {
                output.write(bytes, 0, read);
            }

            return new File(tempFilename).getAbsolutePath();
        } catch (Exception ignored) {

            ignored.getStackTrace();
        } finally {
            closeSilently(input);
            closeSilently(output);
        }
        return null;
    }

    private static String getTempFilename(Context context) throws IOException {
        File outputDir = context.getCacheDir();
        File outputFile = File.createTempFile("image", "tmp", outputDir);
        return outputFile.getAbsolutePath();
    }

    public static void closeSilently(@Nullable Closeable c) {
        if (c == null) return;
        try {
            c.close();
        } catch (Throwable t) {
            // Do nothing
        }
    }

    public static void initSwipeRefreshColor(SwipeRefreshLayout swipeRefreshLayout) {
        swipeRefreshLayout.setColorSchemeResources(R.color.swipe_blue,
                R.color.swipe_green, R.color.swipe_red);
    }

    /**
     * 获取手机IMEI
     *
     * @param context
     * @return
     */
    public static final String getIMEI(Context context) {
        try {
            //实例化TelephonyManager对象
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //获取IMEI号
            String imei = telephonyManager.getDeviceId();
            //在次做个验证，也不是什么时候都能获取到的啊
            if (imei == null) {
                imei = "";
            }
            return imei;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    /**
     * 获取手机IMSI
     */
    public static String getIMSI(Context context) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //获取IMSI号
            String imsi = telephonyManager.getSubscriberId();
            if (null == imsi) {
                imsi = "";
            }
            return imsi;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

}
